package com.joy.ogljoy_01;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView.Renderer;

import com.joy.ogljoy_01.opengl.Graphics;
import com.joy.ogljoy_01.opengl.Screen;
import com.joy.ogljoy_01.opengl.proto.PointF;
import com.joy.ogljoy_01.opengl.proto.SizeF;
import com.joy.ogljoy_01.opengl.ui.FPS;
import com.joy.ogljoy_01.opengl.ui.Image;
import com.joy.ogljoy_01.opengl.ui.Image9;

public class OpenGLRenderer implements Renderer {
	private Image img;
	
	private FPS fps;
	private long lastTime;
	private long nowTime;
	
	private Image9 img9;
	
	private void render(GL10 gl) {
		if(img == null) {
			img = Image.create("icon_boss.png");//224 * 313
//			img.setAnchorPoint(new PointF(0.5f, 0));
			
			fps = FPS.create();
			
			img9 = Image9.create();
//			img9.setPosition(new PointF(50, 500));
			img9.setSize(SizeF.create(Screen.SCALE_W, Screen.SCALE_H));
		}
		
		img9.render();
		
		nowTime = System.currentTimeMillis();
		if(lastTime > 0) {
			float dt = (nowTime - lastTime) * 0.001f;
			fps.update(dt);
		}
		lastTime = nowTime;
		
//		img.setAngle((img.getAngle()+1)%360);
		img.draw(360f, 50f);
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		// TODO Auto-generated method stub

		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		
		render(gl);
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// TODO Auto-generated method stub
		Screen.adapter(width, height);
		
		setGLDefaults(gl);
		beginRender(gl);

	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// TODO Auto-generated method stub
		Graphics.gl = gl;
	}

	public void destroy() {
        android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}
	protected void setGLDefaults(GL10 gl) {
		gl.glViewport(0, 0, Screen.SCREEN_W, Screen.SCREEN_H);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
		gl.glOrthof(0, Screen.SCREEN_W, Screen.SCREEN_H, 0, -1, 1);		
	}
	protected void beginRender(GL10 gl) {
		gl.glEnable(GL10.GL_BLEND);
		gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		// 纹理的使用与开启颜色渲染一样，需要开启纹理功能
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
//		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
	}
	protected void endRender(GL10 gl) {
		gl.glDisable(GL10.GL_BLEND);
		gl.glDisable(GL10.GL_TEXTURE_2D);
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
//		gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
	}
}
